package cn.js189.uqc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.XmlUtil;
import cn.js189.common.constants.BSSUrlConstants;
import cn.js189.common.constants.Constant;
import cn.js189.common.constants.Constants;
import cn.js189.common.domain.ReqHead;
import cn.js189.common.domain.ReqInfo;
import cn.js189.common.domain.RespHead;
import cn.js189.common.domain.RespInfo;
import cn.js189.common.util.CodeConvertUtil;
import cn.js189.common.util.HttpUtil;
import cn.js189.common.util.Utils;
import cn.js189.uqc.common.QXInvoiceService;
import cn.js189.uqc.domain.*;
import cn.js189.uqc.domain.qry.QryChannel;
import cn.js189.uqc.domain.qry.QryCustlevelAndKeyPerson;
import cn.js189.uqc.domain.qry.QryStaff;
import cn.js189.uqc.domain.req.RpeHandleHttpReq;
import cn.js189.uqc.redis.RedisOperation;
import cn.js189.uqc.service.IBssUserQueryService;
import cn.js189.uqc.service.PubAddressIpervice;
import cn.js189.uqc.util.*;
import cn.js189.uqc.util.enums.QryStaffEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.json.XML;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class BssUserQueryServiceImpl implements IBssUserQueryService {
	
	@Resource
	private PubAddressIpervice pubAddressIpervice;
	@Resource
	private SmartBssSystemUtil smartBssSystemUtil;
	@Resource
	private RedisOperation redisOperation;
	@Resource
	private QXInvoiceService qXInvoiceService;
	
	@Override
	public JSONObject checkPurchaseRestrictions(String reqParams) {
		RespInfo respInfo = new RespInfo();
		String tranId = "";
		try {
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			ReqHead head = reqInfo.getHead();
			tranId = head.getTranId();
			JSONObject body = reqInfo.getBody();
			String actionUrl = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.PUR_REST_STRATEGY, head.getLoginNbr());
			String result = JtdqSysUtil.checkPurchaseRestrictions(body, actionUrl);
			return Utils.builderResponse(result, respInfo.getHead(), respInfo, tranId, "code", "", "err");
		} catch (Exception e) {
			log.error("校验限购策略 Exception :{}", e.getMessage());
			return Utils.dealExceptionResp(respInfo.getHead(), tranId, respInfo);
		}
	}
	
	@Override
	public JSONObject checkRcBlackList(String reqParams) {
		log.info("checkRcBlackList input:{}", reqParams);
		RespInfo responseJson = new RespInfo();
		String tranId = "";
		try {
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			ReqHead head = reqInfo.getHead();
			tranId = head.getTranId();
			JSONObject body = reqInfo.getBody();
			String actionUrl = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.CHECK_RC_BLACK, head.getLoginNbr());
			String result = JtdqSysUtil.checkRcBlackList(actionUrl, body);
			return Utils.builderResponse(result, responseJson.getHead(), responseJson, tranId, "code", "", "err");
		} catch (Exception e) {
			log.error("拦截校验接口 Exception :{}", e.getMessage());
			return Utils.dealExceptionResp(responseJson.getHead(), tranId, responseJson);
		}
	}
	
	@Override
	public String documentQuery(String reqParams) {
		JSONObject response;
		log.debug("documentQuery(证件查询接口-10023) input:{}", reqParams);
		RespInfo responseJson = new RespInfo();
		//  获得接口号流水
		String tranId = "";
		try {
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			ReqHead head = reqInfo.getHead();
			JSONObject body = reqInfo.getBody();
			tranId = head.getTranId();
			String actionUrl = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.EOP_QRY_CUSTOMER, head.getLoginNbr());
			String bssRes = smartBssSystemUtil.queryCustomerByAccNum(head, body, actionUrl);
			return EuaCacheUtil.buildBssResponse(body, reqInfo.getHead(), bssRes);
		} catch (Exception e) {
			response = Utils.dealExceptionResp(responseJson.getHead(), tranId, responseJson);
			log.debug("documentQuery(证件查询接口-10023) Exception :{}", e.getMessage());
			return response.toString();
		}
	}
	
	@Override
	public String getActivityInfo(String reqParams) {
		log.debug("活动详情查询接口 input :{}", reqParams);
		RespInfo responseJson = new RespInfo();
		RespHead responseHead = responseJson.getHead();
		responseJson.setHead(responseHead);
		String tranId = "";
		JSONObject response;
		try {
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			JSONObject body = reqInfo.getBody();
			
			String activityId = body.getString(Constants.ACTIVITY_ID);
			String resourceAddr = body.getString("resourceAddr");
			
			String url = EInvoiceUtil.getActivityInfoRemoteUrl(resourceAddr, activityId);
			log.debug("活动详情查询接口URL:{}", url);
			String res = HttpClientHelperForEop.getWithEopAppKey(url);
			log.debug("活动详情查询接口出参:{}", res);
			
			if (!StringUtils.isEmpty(res)) {
				JSONObject resBody = JSON.parseObject(res);
				response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, resBody, "success", "00", responseJson);
			} else {
				response = Utils.dealExceptionRespWithMsgAndStatus(responseHead, tranId, Constants.ERR_INF_NULL, "97", responseJson);
			}
			return response.toString();
		} catch (Exception e) {
			response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
			log.debug("活动详情查询接口 Exception {}", e.getMessage());
			return response.toString();
		}
	}
	
	@Override
	public String getAuthFail(String reqParams) {
		JSONObject response;
		RespInfo responseJson = new RespInfo();
		RespHead responseHead = responseJson.getHead();
		responseJson.setHead(responseHead);
		
		//获取流水号
		String tranId = "";
		try {
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			tranId = reqInfo.getHead().getTranId();
			JSONObject body = reqInfo.getBody();
			
			String url = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.AUTH_FAIL,reqInfo.getHead().getLoginNbr());
			String authDate = body.getString("authDate");
			String serviceType = body.getString("serviceType");
			String userName = body.getString("userName");
			// 组装参数
			StringBuilder sf = new StringBuilder();
			sf.append("<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:lcim=\"http://lcimsforuserinfo.webservice.lcbms.linkage.com\">");
			sf.append("<soapenv:Header/>");
			sf.append("<soapenv:Body>");
			sf.append("<lcim:getAuthFail soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
			sf.append("<in0 xsi:type=\"lcim:GetAuthFailRequest\">");
			sf.append("<authDate xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">");
			sf.append(authDate);
			sf.append("</authDate>");
			sf.append("<servicetype xsi:type=\"xsd:int\">");
			sf.append(serviceType);
			sf.append("</servicetype>");
			sf.append("<username xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">");
			sf.append(userName);
			sf.append("</username>");
			sf.append("</in0>");
			sf.append("</lcim:getAuthFail>");
			sf.append("</soapenv:Body>");
			sf.append("</soapenv:Envelope>");
			
			log.debug("getAuthFail 入参:{}", sf);
			String rsp = HttpUtil.postWebServiceHttpProxy(url, sf.toString(), 10000, "N", "gbk");
			log.debug("getAuthFail 出参:{}", rsp);
			rsp = XmlUtil.format(rsp);
			log.debug("getAuthFail formatXml 转义后:{}", rsp);
			org.json.JSONObject rspJson = XML.toJSONObject(rsp);
			org.json.JSONArray multiRefArr = rspJson.getJSONObject("soapenv:Envelope").getJSONObject("soapenv:Body").getJSONArray("multiRef");
			
			String errorContent = "";
			String content = "";
			String authFailXML = "";
			for (int i = 0; i < multiRefArr.length(); i++) {
				org.json.JSONObject multiRefItem = multiRefArr.getJSONObject(i);
				String id = multiRefItem.getString("id");
				if ("id0".equals(id)) {
					errorContent = multiRefItem.getJSONObject("errorDescription").getString("content");
					authFailXML = multiRefItem.getString("authFailXML");
				} else if ("id1".equals(id)) {
					content = multiRefItem.getString("content");
				}
			}
			
			JSONObject retJson = new JSONObject();
			retJson.put(Constants.STATUS, content);
			retJson.put("msg", errorContent);
			
			if ("0".equals(content)) {
				JSONObject authFailXMLJson = JSON.parseObject(authFailXML);
				JSONObject authfaillist = authFailXMLJson.getJSONObject("authfaillist");
				retJson.put("authfaillist", authfaillist);
			}
			
			response = Utils.dealSuccessResp(responseHead, tranId, retJson, responseJson);
		} catch (Exception e) {
			response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
			return response.toString();
		}
		return response.toString();
	}
	
	@Override
	public String getCustomManagerByProdId(String reqParams) {
		JSONObject response;
		log.info("getCustomManagerByProdId input:{}", reqParams);
		RespInfo responseJson = new RespInfo();
		RespHead responseHead = responseJson.getHead();
		responseJson.setHead(responseHead);
		String responseTime = Utils.getCurrentTime();
		String tranId = "";
		try {
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			ReqHead head = reqInfo.getHead();
			JSONObject body = reqInfo.getBody();
			tranId = head.getTranId();//流水号
			String latnId = body.getString(Constants.LAN_TN_ID);//本地网Id
			String prodId = body.getString("prodId");//产品实例Id
			
			String actionUrl = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.CUSTOM_MANAGER_URL, head.getLoginNbr());
			actionUrl = actionUrl + "?key=" + Constants.DK_KEY + "&LatnId=" + latnId + "&ProdId=" + prodId;
			String res = HttpClientHelperForEop.getWithDcoss(actionUrl, new HashMap<>());
			log.debug("根据客户id查询客户经理信息出参：{}", res);
			if (!StringUtils.isBlank(res)) {
				JSONObject resJson = JSON.parseObject(new String(res.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
				String result = resJson.getString("result");
				if (!StringUtils.isBlank(result)) {
					JSONObject custManagerInfo = resJson.getJSONObject("result");
					responseHead.setStatus("00");
					responseHead.setMsg("成功");
					responseHead.setResponseId(Utils.RSP + tranId);
					responseHead.setResponseTime(responseTime);
					body.put("custManagerInfo", custManagerInfo);
					responseJson.setBody(body);
				} else {
					return Utils.dealExceptionRespWithMsgAndStatus(responseHead, tranId, "查询不到相关数据", "04", responseJson).toString();
				}
				response = (JSONObject) JSON.toJSON(responseJson);
			} else {
				return Utils.dealExceptionRespWithMsgAndStatus(responseHead, tranId, Constants.ERR_NULL, "01", responseJson).toString();
			}
		} catch (Exception e) {
			response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
			log.error("getCustomManagerByProdId Exception :{}", e.getMessage());
			return response.toString();
		}
		return response.toString();
	}
	
	@Override
	public String getGMPropertyRecords(String reqParams) {
		JSONObject response = null;
		RespInfo responseJson = new RespInfo();
		RespHead responseHead = new RespHead();
		responseJson.setHead(responseHead);
		String tranId="";
		try{
			ReqInfo reqInfo = BeanUtil.toBean(reqParams,ReqInfo.class);
			ReqHead head = reqInfo.getHead();// head体
			tranId = head.getTranId();
			JSONObject body = reqInfo.getBody();
			String actionUrl = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.GM_PROPERTIES_URL, head.getLoginNbr());
			String result = JtdqSysUtil.getGMPropertyRecords(body,actionUrl);
			return Utils.builderResponse(result, responseHead, responseJson, tranId,"code","","err").toString();
		} catch (Exception e) {
			response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
			log.debug("获取国漫领取记录 Exception :{}",e.getMessage());
			return response.toString();
		}
	}
	
	@Override
	public String queryStaffInfo(String reqParams) {
		log.debug("查询员工信息 UQC input: {}", reqParams);
		JSONObject response = null;
		RespInfo responseJson = new RespInfo();
		RespHead responseHead = new RespHead();
		String tranId = "";
		try{
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			String areaCode = reqInfo.getHead().getAreaCode();
			String regionId = StaticDataMappingUtil.getRegionByAreaCode(areaCode);
			tranId = reqInfo.getHead().getTranId();
			
			JSONObject body = reqInfo.getBody();
			String staffCode = body.getString("staffCode");
			String staffAccount = body.getString("staffAccount");
			JSONArray staffIds = body.getJSONArray("staffIds");
			String queryType = body.getString("queryType");
			
			QryStaff qryStaff = new QryStaff(regionId, staffCode, staffAccount, staffIds);
			if (!StringUtils.isEmpty(queryType)) {
				if (queryType.contains("1")) {
					qryStaff.addScopeInfos(QryStaffEnum.STAFF);
				}
				if (queryType.contains("2")) {
					qryStaff.addScopeInfos(QryStaffEnum.STAFF_ORG_REL);
				}
				if (queryType.contains("3")) {
					qryStaff.addScopeInfos(QryStaffEnum.STAFF_ATTR);
				}
				if (queryType.contains("4")) {
					qryStaff.addScopeInfos(QryStaffEnum.STAFF_CONTACT_INFO);
				}
			}
			String requestParam = qryStaff.generateContractRoot().toString();
			log.debug("查询员工信息 EOP input: {}", requestParam);
			
			long times = redisOperation.incr(Constant.JS_INTF_QRYSTAFF + areaCode + DateUtils.getNOWDate());
			log.debug("查询员工信息 EOP times: {}", times);
			String result = HttpClientUtils.doPostJSONold(BSSUrlConstants.EOP_QRY_STAFF, requestParam);
			log.debug("查询员工信息 EOP output: {}", result);
			return convertResult(result,responseJson,tranId);
		} catch (Exception e) {
			response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
			log.error("查询员工信息 Exception :{}",e.getMessage());
			return response.toString();
		}
	}
	
	@Override
	public String qryChannel(String reqParams) {
		log.debug("查询渠道信息 UQC input: {}", reqParams);
		JSONObject response = null;
		RespInfo responseJson = new RespInfo();
		RespHead responseHead = new RespHead();
		String tranId = "";
		try{
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			String areaCode = reqInfo.getHead().getAreaCode();
			String regionId = StaticDataMappingUtil.getRegionByAreaCode(areaCode);
			tranId = reqInfo.getHead().getTranId();
			
			JSONObject body = reqInfo.getBody();
			JSONArray orgIds = body.getJSONArray("orgIds");
			String channelNbr = body.getString("channelNbr");
			String channelName = body.getString("channelName");
			String channelClass = body.getString("channelClass");
			String statusCd = body.getString(Constants.STATUS_CD);
			String pageIndex = body.getString("pageIndex");
			String pageSize = body.getString(Constants.PAGE_SIZE);
			
			JSONObject pageInfo = null;
			if(!StringUtils.isEmpty(pageIndex) && !StringUtils.isEmpty(pageSize)){
				pageInfo = new JSONObject();
				pageInfo.put("pageIndex", pageIndex);
				pageInfo.put(Constants.PAGE_SIZE, pageSize);
			}
			
			QryChannel qryChannel = new QryChannel(regionId, orgIds, channelNbr, channelName, channelClass, statusCd, pageInfo);
			String requestParam = qryChannel.generateContractRoot().toString();
			log.debug("查询渠道信息 EOP input: {}", requestParam);
			
			long times = redisOperation.incr(Constant.JS_INTF_QRYCHANNEL + areaCode + DateUtils.getNOWDate());
			log.debug("查询渠道信息 EOP times: {}", times);
			String actionUrl = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.EOP_QRY_CHANNEL, reqInfo.getHead().getLoginNbr());
			String result = HttpClientUtils.doPostJSONold(actionUrl, requestParam);
			log.debug("查询渠道信息 EOP output: {}", result);
			return convertResult(result,responseJson,tranId);
		}catch (Exception e) {
			response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
			log.error("查询渠道信息 Exception :{}",e.getMessage());
			return response.toString();
		}
	}
	
	@Override
	public String rpeHandleHttpReq(String reqParams){
		log.debug("违约金试算 UQC input: {}", reqParams);
		JSONObject response = null;
		RespInfo responseJson = new RespInfo();
		RespHead responseHead = responseJson.getHead();
		responseJson.setHead(responseHead);
		String tranId = "";
		try{
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			String areaCode = reqInfo.getHead().getAreaCode();
			String regionId = StaticDataMappingUtil.getRegionByAreaCode(areaCode);
			tranId = reqInfo.getHead().getTranId();
			
			JSONObject body = reqInfo.getBody();
			String procId = body.getString("procId");
			String procName = body.getString("procName");
			String staffCode = body.getString("staffCode");
			String createDate = body.getString("createDate");
			JSONObject data = body.getJSONObject("data");
			data.put("regionId", regionId);
			data.put("staffCode", staffCode);
			
			RpeHandleHttpReq rpeHandleHttpReq = new RpeHandleHttpReq(regionId, procId, procName, staffCode, createDate, data);
			String requestParam = rpeHandleHttpReq.generateContractRoot().toString();
			log.debug("违约金试算 EOP input: {}", requestParam);
			
			long times = redisOperation.incr(Constant.JS_INTF_RPEHANDLEHTTPREQ + areaCode + DateUtils.getNOWDate());
			log.debug("违约金试算 EOP times: {}", times);
			String actionUrl = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.EOP_RPE_HANDLE_HTTP_REQ, reqInfo.getHead().getLoginNbr());
			String result = HttpClientUtils.doPostJSONold(actionUrl, requestParam);
			log.debug("违约金试算 EOP output: {}", result);
			return convertResult(result,responseJson,tranId);
		}catch (Exception e) {
			response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
			log.error("违约金试算 Exception :{}",e.getMessage());
			return response.toString();
		}
	}

	@Override
	public String calChargeDetailInfo(String reqParams){
		log.debug("订单算费（费用明细） input: {}", reqParams);
		JSONObject response = null;
		RespInfo responseJson = new RespInfo();
		String tranId = "";
		try{
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			String areaCode = reqInfo.getHead().getAreaCode();
			String regionId = StaticDataMappingUtil.getRegionByAreaCode(areaCode);
			tranId = reqInfo.getHead().getTranId();
			
			JSONObject body = reqInfo.getBody();
			String custOrderId = body.getString("custOrderId");
			String custOrderNbr = body.getString("custOrderNbr");
			String orgId = body.getString("orgId");
			String staffCode = body.getString("staffCode");
			String areaCodeArg = body.getString("areaCode");
			
			CalChargeDetailInfo calChargeDetailInfo = new CalChargeDetailInfo(regionId, custOrderId, custOrderNbr,areaCodeArg, orgId, staffCode);
			String requestParam = calChargeDetailInfo.generateContractRoot().toString();
			log.debug("订单算费（费用明细） EOP input: {}", requestParam);
			
			long times = redisOperation.incr(Constant.JS_INTF_CALCHARGEDETAILINFO + areaCode + DateUtils.getNOWDate());
			log.debug("订单算费（费用明细） EOP times: {}", times);
			String actionUrl = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.EOP_CAL_CHARGE_DETAIL_INFO, reqInfo.getHead().getLoginNbr());
			String result = HttpClientUtils.doPostJSONold(actionUrl, requestParam);
			log.debug("订单算费（费用明细） EOP output: {}", result);
			return convertResult(result,responseJson,tranId);
		}catch (Exception e) {
			response = Utils.dealExceptionResp(responseJson.getHead(), tranId, responseJson);
			log.error("订单算费（费用明细） Exception :{}",e.getMessage());
			return response.toString();
		}
	}
	
	@Override
	public String getUserInfo(String reqParams) {
		JSONObject response;
		RespInfo responseJson = new RespInfo();
		RespHead responseHead = new RespHead();
		//获取流水号
		String tranId ="";
		try {
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			tranId = reqInfo.getHead().getTranId();
			JSONObject body = reqInfo.getBody();
			
			String url = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.GET_USER_INFO, reqInfo.getHead().getLoginNbr());
			String serviceType = body.getString("serviceType");
			String userName = body.getString("userName");
			StringBuilder sf = getStringBuilder(serviceType, userName);
			
			log.debug("getUserInfo 入参:{}" , sf);
			String rsp = HttpUtil.postWebServiceHttpProxy(url, sf.toString(), 10000, "N","gbk");
			log.debug("getUserInfo 出参:{}" , rsp);
			rsp = XmlUtil.format(rsp);
			log.debug("getUserInfo formatXml 转义后:{}" , rsp);
			org.json.JSONObject rspJson = XML.toJSONObject(rsp);
			org.json.JSONArray multiRefArr = rspJson.getJSONObject("soapenv:Envelope").getJSONObject("soapenv:Body").getJSONArray("multiRef");
			
			String errorContent = "";
			String content = "";
			String userInfoXML = "";
			for(int i=0;i<multiRefArr.length();i++){
				org.json.JSONObject multiRefItem = multiRefArr.getJSONObject(i);
				String id = multiRefItem.getString("id");
				if("id0".equals(id)){
					errorContent = multiRefItem.getJSONObject("errorDescription").getString("content");
					userInfoXML = multiRefItem.getString("userInfoXML");
				}else if("id1".equals(id)){
					content = multiRefItem.getString("content");
				}
			}
			
			JSONObject retJson = new JSONObject();
			retJson.put(Constants.STATUS, content);
			retJson.put("msg", errorContent);
			
			if("0".equals(content)){
				JSONObject userInfoXMLJson = JSON.parseObject(userInfoXML);
				JSONObject userinfo = userInfoXMLJson.getJSONObject("userinfo");
				retJson.put("userinfo", userinfo);
			}
			
			response = Utils.dealSuccessResp(responseHead, tranId, retJson, responseJson);
		}catch (Exception e) {
			response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
			return response.toString();
		}
		return response.toString();
	}
	
	@Override
	public String getNumInfoByCardNo(String reqParams) {
		log.debug("根据卡号获取用户号码 input: {}", reqParams);
		JSONObject response = null;
		RespInfo responseJson = new RespInfo();
		RespHead responseHead = new RespHead();
		responseJson.setHead(responseHead);
		String tranId = "";
		try {
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			ReqHead head = reqInfo.getHead();
			JSONObject body = reqInfo.getBody();
			tranId = head.getTranId();
			
			String areaCode = head.getAreaCode();
			// 获取nj.js.cn这种格式
			String areaCode2 = INocBillServiceImpl.areaIdMap.get(INocBillServiceImpl.areaCodeMap.get(areaCode));
			String cardNo = body.getString("cardNo");
			
			JSONObject reqJson = new JSONObject();
			JSONObject inputMessageJson = new JSONObject();
			JSONObject msgBody = new JSONObject();
			msgBody.put("areaCode", areaCode2);
			msgBody.put("cardNo", cardNo);
			
			JSONObject msgHead = new JSONObject();
			msgHead.put("sourceSystem", "CRM");
			msgHead.put("uuid", IdUtil.simpleUUID());
			msgHead.put("reqTime", DateUtils.getDateString(new Date(),DateUtils.STRING_DATE_FORMAT));
			
			inputMessageJson.put("msgBody", msgBody);
			inputMessageJson.put("msgHead", msgHead);
			reqJson.put("inputMessage", inputMessageJson);
			
			Map<String,String> headMap = new HashMap<>();
			headMap.put("X-APP-ID", "6f4b6566a2a34cfdeed05486b78539f2");
			headMap.put("X-APP-KEY", "aae578b9e72b3cae1431d8f1bcc75294");
			log.info("BssSystemImpl.getNumInfoByCardNo body：{}" , reqJson);
			String actionUrl = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.GET_NUM_INFO_BY_CARD_NO_URL, head.getLoginNbr());
			String resp = HttpClientHelperForEop.postWithHeader(actionUrl, reqJson.toString(), headMap, 30000);
			log.info("BssSystemImpl.getNumInfoByCardNo resp：{}" , resp);
			if (StringUtils.isBlank(resp)) {
				String resultMsg = Constants.ERR_NULL;
				return BSSHelper.getErrInfo("99", resultMsg).toString();
			}
			JSONObject respJson = JSON.parseObject(resp);
			return  Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, respJson, "success", "00", responseJson).toString();
		}catch (Exception e) {
			response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
			return response.toString();
		}
	}
	
	@Override
	public String getSign(){
		try{
			return qXInvoiceService.getSign();
		}catch(Exception ex){
			log.debug("getSign方法异常：{}", ex.getMessage());
			return "";
		}
	}
	
	@Override
	public String getUserDet(String reqParams) {
		JSONObject response = null;
		RespInfo responseJson = new RespInfo();
		RespHead responseHead = new RespHead();
		//获取流水号
		String tranId ="";
		try {
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			tranId = reqInfo.getHead().getTranId();
			JSONObject body = reqInfo.getBody();
			
			String url = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.GET_USER_DET, reqInfo.getHead().getLoginNbr());
			String serviceType = body.getString("serviceType");
			String userName = body.getString("userName");
			String beginTime = body.getString("beginTime");
			String endTime = body.getString("endTime");
			long beginTimeLong = DateUtils.formateDateString(beginTime, "yyyyMMddHHmm").getTime();
			long endTimeLong = DateUtils.formateDateString(endTime, "yyyyMMddHHmm").getTime();
			
			// 组装参数
			StringBuilder sf = new StringBuilder();
			sf.append("<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:lcim=\"http://lcimsforuserinfo.webservice.lcbms.linkage.com\">");
			sf.append("<soapenv:Header/>");
			sf.append("<soapenv:Body>");
			sf.append("<lcim:getUserDet soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
			sf.append("<in0 xsi:type=\"lcim:GetUserDetRequest\">");
			sf.append("<beginTime xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">");
			sf.append(beginTimeLong);
			sf.append("</beginTime>");
			sf.append("<endTime xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">");
			sf.append(endTimeLong);
			sf.append("</endTime>");
			sf.append("<servicetype xsi:type=\"xsd:int\">");
			sf.append(serviceType);
			sf.append("</servicetype>");
			sf.append("<username xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">");
			sf.append(userName);
			sf.append("</username>");
			sf.append("</in0>");
			sf.append("</lcim:getUserDet>");
			sf.append("</soapenv:Body>");
			sf.append("</soapenv:Envelope>");
			
			log.debug("getUserDet 入参:{}" , sf.toString());
			String rsp = HttpUtil.postWebServiceHttpProxy(url, sf.toString(), 10000, "N","gbk");
			log.debug("getUserDet 出参:{}" , rsp);
			rsp = XmlUtil.format(rsp);
			log.debug("getUserDet formatXml 转义后:{}" , rsp);
			org.json.JSONObject rspJson = XML.toJSONObject(rsp);
			org.json.JSONArray multiRefArr = rspJson.getJSONObject("soapenv:Envelope").getJSONObject("soapenv:Body").getJSONArray("multiRef");
			
			String errorContent = "";
			String content = "";
			String userDetXML = "";
			for(int i=0;i<multiRefArr.length();i++){
				org.json.JSONObject multiRefItem = multiRefArr.getJSONObject(i);
				String id = multiRefItem.getString("id");
				if("id0".equals(id)){
					errorContent = multiRefItem.getJSONObject("errorDescription").getString("content");
					userDetXML = multiRefItem.getString("userDetXML");
				}else if("id1".equals(id)){
					content = multiRefItem.getString("content");
				}
			}
			
			JSONObject retJson = new JSONObject();
			retJson.put("status", content);
			retJson.put("msg", errorContent);
			
			if("0".equals(content)){
				JSONObject userDetXMLJson = JSON.parseObject(userDetXML);
				JSONObject userdetlist = userDetXMLJson.getJSONObject("userdetlist");
				retJson.put("userdetlist", userdetlist);
			}
			
			response = Utils.dealSuccessResp(responseHead, tranId, retJson, responseJson);
		}catch (Exception e) {
			response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
			return response.toString();
		}
		return response.toString();
	}
	
	@Override
	public String getUserOnline(String reqParams) {
		JSONObject response = null;
		RespInfo responseJson = new RespInfo();
		RespHead responseHead = new RespHead();
		//获取流水号
		String tranId ="";
		try {
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			tranId = reqInfo.getHead().getTranId();
			JSONObject body = reqInfo.getBody();
			String actionUrl = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.GET_USER_ONLINE, reqInfo.getHead().getLoginNbr());
			String serviceType = body.getString("serviceType");
			String userName = body.getString("userName");
			StringBuilder sf = new StringBuilder();
			sf.append("<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:lcim=\"http://lcimsforuserinfo.webservice.lcbms.linkage.com\">");
			sf.append("<soapenv:Header/>");
			sf.append("<soapenv:Body>");
			sf.append("<lcim:getUserOnline soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
			sf.append("<in0 xsi:type=\"lcim:GetUserOnlineRequest\">");
			sf.append("<servicetype xsi:type=\"xsd:int\">");
			sf.append(serviceType);
			sf.append("</servicetype>");
			sf.append("<username xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">");
			sf.append(userName);
			sf.append("</username>");
			sf.append("</in0>");
			sf.append("</lcim:getUserOnline>");
			sf.append("</soapenv:Body>");
			sf.append("</soapenv:Envelope>");
			log.debug("getUserOnline 入参:{}" , sf);
			String rsp = HttpUtil.postWebServiceHttpProxy(actionUrl, sf.toString(), 10000, "N","gbk");
			log.debug("getUserOnline 出参:{}" , rsp);
			rsp = XmlUtil.format(rsp);
			log.debug("getUserOnline formatXml 转义后:{}" , rsp);
			org.json.JSONObject rspJson = XML.toJSONObject(rsp);
			org.json.JSONArray multiRefArr = rspJson.getJSONObject("soapenv:Envelope").getJSONObject("soapenv:Body").getJSONArray("multiRef");
			
			String errorContent = "";
			String content = "";
			String userOnlineXML = "";
			for(int i=0;i<multiRefArr.length();i++){
				org.json.JSONObject multiRefItem = multiRefArr.getJSONObject(i);
				String id = multiRefItem.getString("id");
				if("id0".equals(id)){
					errorContent = multiRefItem.getJSONObject("errorDescription").getString("content");
					userOnlineXML = multiRefItem.getString("userOnlineXML");
				}else if("id1".equals(id)){
					content = multiRefItem.getString("content");
				}
			}
			
			JSONObject retJson = new JSONObject();
			retJson.put("status", content);
			retJson.put("msg", errorContent);
			
			if("0".equals(content)){
				JSONObject userOnlineXMLJson = JSON.parseObject(userOnlineXML);
				JSONObject useronlininfolist = userOnlineXMLJson.getJSONObject("useronlinelist");
				retJson.put("useronlinelist", useronlininfolist);
			}
			
			response = Utils.dealSuccessResp(responseHead, tranId, retJson, responseJson);
		}catch (Exception e) {
			response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
			return response.toString();
		}
		return response.toString();
	}
	
	@Override
	public String qryCustlevelAndKeyPerson(String reqParams) {
		log.debug("查询政企客户等级、关键人联系人  UQC input: {}", reqParams);
		JSONObject response = null;
		RespInfo responseJson = new RespInfo();
		RespHead responseHead = new RespHead();
		String tranId = "";
		try{
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			String areaCode = reqInfo.getHead().getAreaCode();
			String regionId = StaticDataMappingUtil.getRegionByAreaCode(areaCode);
			
			JSONObject body = reqInfo.getBody();
			String accNum = body.getString("accNum");
			String certNum = body.getString("certNum");
			String custId = body.getString("custId");
			List<Integer> queryContent = body.getJSONArray("queryContent").toJavaList(Integer.class);
			QryCustlevelAndKeyPerson qryCustlevelAndKeyPerson = new QryCustlevelAndKeyPerson(accNum, certNum, custId, queryContent, regionId);
			String requestParam = qryCustlevelAndKeyPerson.generateContractRoot().toString();
			log.debug("查询政企客户等级、关键人联系人 EOP input: {}", requestParam);
			
			String result = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.EOP_QRY_CUST_LEVEL, reqInfo.getHead().getLoginNbr());
			log.debug("查询政企客户等级、关键人联系人 output: {}", result);
			
			if (!StringUtils.isEmpty(result)) {
				JSONObject svcCont = JSON.parseObject(result).getJSONObject("contractRoot").getJSONObject("svcCont");
				if (null != svcCont) {
					String code = svcCont.getString("resultCode");
					String resultMsg = svcCont.getString("resultMsg");
					
					if (StringUtils.equals("0", code)) {
						
						JSONObject respBody = svcCont.getJSONObject(Constants.RESULT_OBJECT);
						
						response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, respBody, "success", "00", responseJson);
						
					} else {
						response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, null, resultMsg, code, responseJson);
					}
				} else {
					response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, null, Constants.ERR_OBJ_NULL, "97", responseJson);
				}
				
			} else {
				response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, null, Constants.ERR_INF_NULL, "98", responseJson);
			}
			
			return response.toString();
			
		}catch (Exception e) {
			response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
			log.error("查询政企客户等级、关键人联系人Exception :{}",e.getMessage());
			return response.toString();
		}
		
	}
	
	@Override
	public String qryCustomerWithNoFilter(String reqParams) {
		JSONObject response = null;
		log.debug("qryCustomerWithNoFilter(查询客户接口) input:{}" , reqParams);
		RespInfo responseJson = new RespInfo();
		RespHead responseHead = new RespHead();
		//  获得接口号流水
		String tranId = "";
		try {
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			ReqHead head = reqInfo.getHead();
			JSONObject body = reqInfo.getBody();
			String actionUrl = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.EOP_QRY_CUSTOMER, head.getLoginNbr());
			return SmartBssSystemUtil.qryCustomerWithNoFilter(head, body,actionUrl);
		}catch (Exception e) {
			response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
			log.debug("qryCustomerWithNoFilter(查询客户接口) Exception :{}" , e.getMessage());
			return response.toString();
		}
	}
	
	@Override
	public String qryCustomerOrderByType(String reqParams) {
		JSONObject response = null;
		log.info("qryCustomerOrderByType input:{}" , reqParams);
		RespInfo responseJson = new RespInfo();
		RespHead responseHead = new RespHead();
		//  获得接口号流水
		String tranId = "";
		try {
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			ReqHead head = reqInfo.getHead();// head体
			JSONObject body = reqInfo.getBody();
			//流水号
			tranId = head.getTranId();
			String regionId = StaticDataMappingUtil.getRegionByAreaCode(head.getAreaCode());
			String custId = body.getString("custId");
			String prodInstId = body.getString("prodInstId");
			String accNum = body.getString("accNum");
			String isSendAutograph = body.getString("isSendAutograph");
			String actionUrl = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.EOP_QRY_CUSTOMER_ORDER_TYPE, head.getLoginNbr());
			String bssRes = SmartBssSystemUtil.qryCustomerOrderByType(regionId,custId,prodInstId,accNum,isSendAutograph,actionUrl);
			return EuaCacheUtil.buildBssResponse(body,reqInfo.getHead(),bssRes);
		}catch (Exception e) {
			response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
			return response.toString();
		}
	}
	
	@Override
	public String qryFullAddressFromOSS(String reqParams) {
		log.debug("qryFullAddressFromOSSNew request ：{}" , reqParams);
		JSONObject response = null;
		RespInfo responseJson = new RespInfo();
		RespHead responseHead = new RespHead();
		String tranId="";
		try{
			ReqInfo reqInfo = BeanUtil.toBean(reqParams, ReqInfo.class);
			ReqHead head = reqInfo.getHead();// head体
			JSONObject body = reqInfo.getBody();
			String partitionId = CodeConvertUtil.getThreeAreaCode(head.getAreaCode());
			String address = body.getString("address");
			String url = pubAddressIpervice.getActionUrl(UqcAddressCodeConstants.QRY_FULL_ADDRESS_FORM_OSS, head.getLoginNbr());
			JSONObject paramJson = new JSONObject();
			paramJson.put("partitionId", partitionId);
			paramJson.put("address", address);
			if(body.containsKey("minScore")&&!("".equals(body.getString("minScore")))){
				paramJson.put("minScore", body.getString("minScore"));
			}
			if(body.containsKey("areaId")&&!("".equals(body.getString("areaId")))){
				paramJson.put("areaId", body.getString("areaId"));
			}
			log.debug("qryFullAddressFromOSSNew paramJson ：{}" , paramJson);
			String result = HttpClientHelperForEop.postToBill(url,paramJson.toString(), head.getAreaCode());
			log.debug("qryFullAddressFromOSSNew result ：{}" , result);
			if(CharSequenceUtil.isBlank(result)){
				return Utils.dealExceptionRespWithMsgAndStatus(responseHead,tranId,"OSS接口出错","01",responseJson).toString();
			}
			JSONObject resultJson = JSON.parseObject(result);
			if(resultJson.containsKey("state")&& "SUC".equals(resultJson.getString("state"))){
				resultJson.put(Constants.STATUS, "0");
			}else{
				resultJson.put(Constants.STATUS, "1");
			}
			response = Utils.builderResponse(resultJson.toString(), responseHead, responseJson, tranId, Constants.STATUS, "","state");
			if (body.containsKey(Constants.UQCENCFLAG)) {
				response = EuaCacheUtil.getEncResponse(response, reqInfo.getHead());
			}
		}catch (Exception e) {
			response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
			log.debug("智慧选址接口181113  Exception :{}",e.getMessage());
			return response.toString();
		}
		return response.toString();
	}
	
	
	/**
	 * xml组装
	 * @param serviceType 业务类型
	 * @param userName 用户名称
	 * @return 结果
	 */
	private StringBuilder getStringBuilder(String serviceType, String userName) {
		StringBuilder sf = new StringBuilder();
		sf.append("<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:lcim=\"http://lcimsforuserinfo.webservice.lcbms.linkage.com\">");
		sf.append("<soapenv:Header/>");
		sf.append("<soapenv:Body>");
		sf.append("<lcim:getUserInfo soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
		sf.append("<in0 xsi:type=\"lcim:GetUserInfoRequest\">");
		sf.append("<servicetype xsi:type=\"xsd:int\">");
		sf.append(serviceType);
		sf.append("</servicetype>");
		sf.append("<username xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">");
		sf.append(userName);
		sf.append("</username>");
		sf.append("</in0>");
		sf.append("</lcim:getUserInfo>");
		sf.append("</soapenv:Body>");
		sf.append("</soapenv:Envelope>");
		return sf;
	}
	
	/**
	 * 返回结果
	 *
	 * @param result 参数
	 * @return 结果
	 */
	public String convertResult(String result, RespInfo responseJson,String tranId){
		JSONObject response;
		if (!StringUtils.isEmpty(result)) {
			JSONObject svcCont = JSON.parseObject(result).getJSONObject("contractRoot").getJSONObject("svcCont");
			if (null != svcCont) {
				String code = svcCont.getString("resultCode");
				String resultMsg = svcCont.getString("resultMsg");
				if (StringUtils.equals("0", code)) {
					JSONObject respBody = svcCont.getJSONObject(Constants.RESULT_OBJECT);
					response = Utils.dealSuccessRespWithMsgAndStatus(responseJson.getHead(), tranId, respBody, "success", "00", responseJson);
				} else {
					response = Utils.dealSuccessRespWithMsgAndStatus(responseJson.getHead(), tranId, null, resultMsg, code, responseJson);
				}
			} else {
				response = Utils.dealSuccessRespWithMsgAndStatus(responseJson.getHead(), tranId, null, Constants.ERR_OBJ_NULL, "97", responseJson);
			}
		} else {
			response = Utils.dealSuccessRespWithMsgAndStatus(responseJson.getHead(), tranId, null, Constants.ERR_INF_NULL, "98", responseJson);
		}
		return response.toString();
	}
	
}
